<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<!--//application/x-www-form-urlencoded 序列化表单-->
<form action="" method="post"  enctype="multipart/form-data">
    姓名:<input type="text" name="username" id=""/><br/>
    密码:<input type="password" name="password" id=""/><br/>
    头像:<input type="file" name="headpic" id=""/><br/>
    <input type="submit" value="注册"/>
    <input type="button" value="提交" id="btn"/>
</form>
<script>
    function serialize(form){
        var elements = Array.prototype.slice.call(form.elements);
        var data = [];
        elements.forEach(function(ele){
            var type = ele.type;
            switch (type){
                case 'text':
                    data.push(ele.name+'='+ele.value);
                    break;
                case 'password':
                    data.push(ele.name+'='+ele.value);
                    break;
                case 'file':
                    data.push(ele.name+'='+ele.value);
                    break;
                case 'radio':
                    break;
                default:


            }
        })
        return data.join('&');//返回查询字符串格式
    }
    function toJson(form){
        var elements = Array.prototype.slice.call(form.elements);
        var data = {};
        elements.forEach(function(ele){
            var type = ele.type;
            switch (type){
                case 'text':
                case 'password':
                case 'file':
                    data[ele.name] = ele.value;
                    break;
                case 'radio':
                    break;
                default:

            }
        })
        return JSON.stringify(data);
    }
    var oBtn = document.getElementById('btn');
    oBtn.onclick = function(){
        var oForm = document.getElementsByTagName('form')[0];
//        var data = toJson(oForm);//将数据转成json
        var data = serialize(oForm);//将数据转成查询字符串
        var xhr = new XMLHttpRequest();
        xhr.open('POST','/post',true);
//        发送序列化表单,默认的类型
//        xhr.setRequestHeader('Content-Type','application/json');//发json数据
        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');//发查询字符串
        xhr.onreadystatechange = function(){
            if(xhr.readyState==4&&xhr.status==200){

            }
        }

        xhr.send(data);
    }
</script>
</body>
</html>